package com.csw.flink.window

import java.util.Properties

import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer

object Demo03CountWindow {
  def main(args: Array[String]): Unit = {

    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    //创建配置文件对象
    val properties = new Properties()
    properties.setProperty("bootstrap.servers", "master:9092,node1:9092,node2:9092")
    /**
      * 创建kafka消费者
      */
    val consumer: FlinkKafkaConsumer[String] = new FlinkKafkaConsumer[String]("test_topicl", new SimpleStringSchema(), properties)

    //读取最新数据
    consumer.setStartFromLatest()

    val kafkaDS: DataStream[String] = env.addSource(consumer)

    val kvDS: KeyedStream[(String, Int), String] = kafkaDS.map((_, 1)).keyBy(_._1)

    /**
      *
      * count window：当每一个key数据量达到一定数量时进行计算
      *
      * countWindow(10)：滚动
      * countWindow(10,2)：滑动
      */

    kvDS
      .countWindow(10,2)
      .sum(1)
      .print()

    env.execute()
  }
}
